import router from "@/router";
import axios from "axios";

//全局配置axios

axios.defaults.apiUrl = "http://localhost:5000"
//请求拦截
axios.interceptors.request.use(config => {  
    //如果本地存储有token（代表已登录），请求都携带该token发送请求  
    if (localStorage.getItem('token')) {        
        config.headers['Authorization'] = localStorage.getItem('token');
    }
    return config;
}, error => {
    Promise.reject(error)
})

//响应拦截
axios.interceptors.response.use(res => {
    //   return res; 
    if (res.code ==0 || res.code == 200) {
        // code值为 0 或 200 时视为成功
        return res.data
     }
return res.data;
    
}, error => {
    // console.log("status："+error.response.status)
    if (error.response.status == 401) {
        alert('您没有访问权限，请先前往登录');
        //跳转到登录页
        router.push('/login')
    }
    return Promise.reject(error)
})

export default axios;